﻿using FwDl.Common;
using SuperSocket.ClientEngine;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BindCodes
{
    public partial class FrmMain : Form
    {
        bool bIsRunning = false, bClose = false, bBuffDataChange = false, bReset = false;
        long ticks = 0;
        string dirLog, dirExp, strBatch, strPZWH;
        int test = 0;
        int logQty = 0;
        ConcurrentQueue<string> codeRlt, codeZS;
        List<string> codeHand;
        Thread td = null;
        string cmdFail, cmdPick, codeReg;
        string h1, h2;
        Dictionary<string, string> codeBinded;//key=关联码，value=24位码
        Dictionary<string, string> code2Bind;
        object objPrc = new object();
        int handQty = 0;
        DataTable dtCodes;
        FrmExp frmExp;
        FrmAllRltCodes frmAllCode;
        FrmProcessBar progBar = null;
        string batchOld = "";

        AsyncTcpSession client;
        string srvIP;
        int srvPort;
        bool bCheckPZWH;
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            #region 设置状态栏文本

            string product = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0] as AssemblyProductAttribute).Product;
            string ver = string.Format(" V{0}.{1}.{2}",
                Assembly.GetExecutingAssembly().GetName().Version.Major,
                Assembly.GetExecutingAssembly().GetName().Version.Minor,
                Assembly.GetExecutingAssembly().GetName().Version.Build);

            this.Text += string.Format(" {0}", ver);
            #endregion

            #region 初始化系统变量
            dirLog = Path.Combine(Application.StartupPath, "log");
            if (!Directory.Exists(dirLog))
            {
                Directory.CreateDirectory(dirLog);
            }

            dirExp = Path.Combine(Application.StartupPath, "exception");
            if (!Directory.Exists(dirExp))
            {
                Directory.CreateDirectory(dirExp);
            }

            //bool n = ValidateHelper.IsNumber("12309280945723980");
            //bool n2 = ValidateHelper.IsNumber("A12309280945723980");

            //Console.WriteLine($"{n},{n2}");

            cmdFail = ConfigurationHelper.AppGetString("cmdFail");
            cmdPick = ConfigurationHelper.AppGetString("cmdPick");
            codeReg = ConfigurationHelper.AppGetString("codeReg");

            codeHand = new List<string>();
            codeRlt = new ConcurrentQueue<string>();
            codeZS = new ConcurrentQueue<string>();

            codeBinded = new Dictionary<string, string>();
            code2Bind = new Dictionary<string, string>();

            txtBatch.Text = ConfigurationHelper.AppGetString("batch");

            if (!ConfigurationHelper.HasSetting("pzwh"))
            {
                ConfigurationHelper.AppSet("pzwh", "");//默认50万
            }

            txtPZWH.Text = ConfigurationHelper.AppGetString("pzwh");

            string err = "";
            dtCodes = SqlHelper.ExecuteTable("SELECT TOP 0 * FROM [CodeRltInfo]", ref err);

            if (!string.IsNullOrEmpty(err))
            {
                MessageBox.Show("数据库连接失败：" + err);
                AppendExp("数据库连接失败：" + err);
                Close();
                return;
            }

            #endregion

            string[] items = ConfigurationHelper.AppGetString("codePort").Split(new char[] { ','});
            serialPort1.PortName = items[0];
            serialPort1.BaudRate = Convert.ToInt32(items[1]);
            serialPort1.NewLine = "\r\n";
            serialPort1.Encoding = Encoding.GetEncoding(ConfigurationHelper.AppGetString("encode"));

            try
            {
                serialPort1.Open();
            }
            catch (Exception exp)
            {
                MessageBox.Show("追溯码扫描器打开失败：" + exp.Message);
                AppendExp("追溯码扫描器打开失败：" + exp.Message);
                Close();
                return;
            }


            items = ConfigurationHelper.AppGetString("rltPort").Split(new char[] { ',' });

            client = new AsyncTcpSession();
            client.Connected += Client_Connected;
            client.Closed += Client_Closed;

            try
            {
                srvIP = items[0];
                srvPort = Convert.ToInt32(items[1]);
                client.Connect(new IPEndPoint(IPAddress.Parse(srvIP), srvPort));
            }
            catch (Exception exp)
            {
                MessageBox.Show("瓶盖码扫描器打开失败：" + exp.Message);
                AppendExp("瓶盖码扫描器打开失败：" + exp.Message);
                Close();
                return;
            }

            items = ConfigurationHelper.AppGetString("handPort").Split(new char[] { ',' });
            serialPort3.PortName = items[0];
            serialPort3.BaudRate = Convert.ToInt32(items[1]);
            serialPort3.Encoding = Encoding.GetEncoding(ConfigurationHelper.AppGetString("encode"));
            serialPort3.NewLine = "\r";
            try
            {
                serialPort3.Open();
            }
            catch (Exception exp)
            {
                AppendExp("验证扫描器打开失败：" + exp.Message);
            }

            serialPort1.DataReceived -= serialPort1_DataReceived;

            if (!SqlHelper.IfColumnExist("CodeRltInfo", "pzwh"))
            {
                string msg = string.Empty;

                if (!SqlHelper.AddColumn("CodeRltInfo", "pzwh", "varchar(50) NULL", ref msg))
                {
                    msg = "CodeRltInfo表无法添加pzwh列";
                    return;
                }
            }

            timer1.Enabled = true;
            timer1.Start();

        }

        private void Client_Closed(object sender, EventArgs e)
        {
            if (!bClose)
            {
                AppendExp("客户端异常断开，开启自动重连...");

                try
                {
                    client.Close();
                    client = new AsyncTcpSession();
                    client.Connected += Client_Connected;
                    client.Closed += Client_Closed;

                    if (bIsRunning)
                    {
                        client.DataReceived += Client_DataReceived;
                    }

                    client.Connect(new IPEndPoint(IPAddress.Parse(srvIP), srvPort));
                }
                catch (Exception)
                {

                }
            }
        }

        private void Client_DataReceived(object sender, DataEventArgs e)
        {
            string c2 = Encoding.UTF8.GetString(e.Data, 0, e.Length).Trim();

            //c2 = c2.Substring(1);//去掉前缀

            if (c2.Equals(cmdFail, StringComparison.OrdinalIgnoreCase))
            {
                Pick();
                AppendLog($"瓶盖码读码失败");
                codeRlt.Enqueue(cmdFail);
            }
            else
            {
                //必须纯数字
                if (ValidateHelper.IsNumber(c2))
                {
                    if (codeBinded.ContainsKey(c2) || code2Bind.ContainsKey(c2) || codeRlt.Contains(c2))
                    {
                        Pick();
                        AppendLog($"瓶盖码重复：{c2}");
                        codeRlt.Enqueue(cmdFail);
                    }
                    else
                    {
                        codeRlt.Enqueue(c2);
                    }
                }
                else
                {
                    Pick();
                    AppendLog($"瓶盖码非法：{c2}");
                    codeRlt.Enqueue(cmdFail);
                }

            }

            bBuffDataChange = true;
        }

        private void Client_Connected(object sender, EventArgs e)
        {
            AppendLog("瓶盖码扫描器连成功！");

        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            bClose = true;
            if (frmExp!=null)
            {
                try
                {
                    frmExp.Close();
                }
                catch (Exception)
                {
                }
            }

            if (frmAllCode != null)
            {
                try
                {
                    frmAllCode.Close();
                }
                catch (Exception)
                {
                }
            }

            if (client!=null && client.IsConnected)
            {
                client.Close();
            }

            timer1.Stop();

            System.Environment.Exit(0);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bIsRunning)
            {
                MessageBox.Show("正在运行，无法退出...");
                e.Cancel = true;
                return;
            }

            if (codeZS.Count>0 && codeRlt.Count>0)
            {
                if (MessageBox.Show("尚有缓存数据未保存，是否强制退出？", "请注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {

                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (btnRun.Text == "启动")
            {
                if (string.IsNullOrEmpty(txtBatch.Text.Trim()))
                {
                    MessageBox.Show("批次号不能为空！");
                    txtBatch.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtPZWH.Text.Trim()))
                {
                    MessageBox.Show("批准文号不能为空！");
                    txtPZWH.Focus();
                    return;
                }

                if (client==null || !client.IsConnected)
                {
                    MessageBox.Show("瓶盖读码器未连接成功！");
                    return;
                }

                if (!string.IsNullOrEmpty(batchOld) && batchOld.Equals(txtBatch.Text.Trim()))
                {
                    bIsRunning = true;
                    btnRun.Text = "停止";
                    btnRun.BackColor = Color.Red;
                    strBatch = txtBatch.Text;
                    strPZWH = txtPZWH.Text;
                    btnExp.Enabled = true;

                    serialPort1.DiscardInBuffer();
                    serialPort1.DataReceived += serialPort1_DataReceived;

                    client.DataReceived += Client_DataReceived;
                    //serialPort2.DataReceived += serialPort2_DataReceived;

                    bCheckPZWH = chkCheckPZWH.Checked;
                    chkCheckPZWH.Enabled = false;
                }
                else
                {
                    codeBinded.Clear();

                    btnRun.Enabled = false;
                    
                    this.backgroundWorker1.RunWorkerAsync(); // 运行 backgroundWorker 组件

                    progBar = new FrmProcessBar(this.backgroundWorker1);// 显示进度条窗体
                    progBar.Text = "加载任务信息";
                    progBar.Show(this);
                }

            }
            else
            {
                bIsRunning = false;
                chkCheckPZWH.Enabled = true;
                btnRun.Text = "启动";
                btnRun.BackColor = Color.Green;
                btnExp.Enabled = false;
                serialPort1.DataReceived -= serialPort1_DataReceived;
                client.DataReceived -= Client_DataReceived;
                //serialPort2.DataReceived -= serialPort2_DataReceived;

            }

            txtBatch.Enabled = !bIsRunning;
            txtPZWH.Enabled = !bIsRunning;
            //btnReset.Enabled = bIsRunning;
        }


        public void AppendLog(string s)
        {
            try
            {
                string log = string.Format("[{0}] {1}\r\n", DateTime.Now.ToString("HH:mm:ss"), s);
                Console.WriteLine(log);

                string path = string.Format("{0}\\{1}_log.txt", dirLog, DateTime.Now.ToString("yyyyMMdd"));
                File.AppendAllText(path, log);

                AppendMsg(s);
            }
            catch (Exception)
            {

            }
        }

        public void AppendExp(string s)
        {
            try
            {
                string log = string.Format("[{0}] {1}\r\n", DateTime.Now.ToString("HH:mm:ss"), s);
                Console.WriteLine(log);

                string path = string.Format("{0}\\{1}_exception.txt", dirExp, DateTime.Now.ToString("yyyyMMdd"));
                File.AppendAllText(path, log);

                AppendMsg(s);
            }
            catch (Exception)
            {

            }
        }

        private void btnExp_Click(object sender, EventArgs e)
        {
            FrmExp frm = new FrmExp();
            
            frmExp = frm;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                switch (frm.Opr)
                {
                    case 0://删除
                        ThreadPool.QueueUserWorkItem(new WaitCallback(s=> 
                        {
                            List<string> codes = s as List<string>;
                            List<string> sqls = new List<string>();
    
                            lock (objPrc)
                            {
                                foreach (var item in codes)
                                {
                                    if (item.Trim().Length>=24)
                                    {
                                        if (SYZSCheck24Bit(item))
                                        {
                                            string bit24 = SYZSGet24Bit(item);
                                            string key = "";

                                            foreach (KeyValuePair<string, string> kvp in code2Bind)
                                            {
                                                if (kvp.Value.Equals(bit24))
                                                {
                                                    key = kvp.Key;
                                                    break;
                                                }
                                            }

                                            code2Bind.Remove(key);

                                            key = "";

                                            foreach (KeyValuePair<string, string> kvp in codeBinded)
                                            {
                                                if (kvp.Value.Equals(bit24))
                                                {
                                                    key = kvp.Key;
                                                    break;
                                                }
                                            }

                                            codeBinded.Remove(key);

                                            sqls.Add($"delete from CodeRltInfo where batch='{strBatch}' and rltCode='{key}' and pzwh='{strPZWH}'");
                                        }
                                    }
                                    else
                                    {
                                        code2Bind.Remove(item);
                                        codeBinded.Remove(item);

                                        sqls.Add($"delete from CodeRltInfo where batch='{strBatch}' and rltCode='{item}' and pzwh='{strPZWH}'");
                                    }
                                    
                                }
                                
                                bBuffDataChange = true;
                            }
                            if (sqls.Count > 0)
                            {
                                string err = "";
                                if (!SqlHelper.ExecuteSqlTran(sqls.ToArray(), ref err))
                                {
                                    AppendExp("关联数据删除失败：" + err);
                                }
                                else
                                {
                                    CallCtrlWithThreadSafety.SetText(lbQtyTotal, codeBinded.Count.ToString(), this);
                                    AppendExp("关联数据删除成功");
                                }
                            }

                        }), new List<string>(frm.codes));
                        break;
                    case 1://手动关联
                        for (int i = 0; i+1 < frm.codes.Count; i+=2)
                        {
                            string c2 = frm.codes[i];
                            string c1 = frm.codes[i + 1];
                            string bit24;

                            if (!SYZSCheck24Bit(c1))
                            {
                                AppendLog($"追溯码非法：{c1}");
                                continue;
                            }
                            else
                            {
                                bit24 = SYZSGet24Bit(c1);

                                if (codeBinded.ContainsValue(bit24) || code2Bind.ContainsValue(bit24))
                                {
                                    AppendLog($"追溯码重复：{c1}");
                                    continue;
                                }

                            }

                            if (codeBinded.ContainsKey(c2) || code2Bind.ContainsKey(c2))
                            {
                                AppendLog($"瓶盖码重复：{c2}");
                                continue;
                            }


                            lock (objPrc)
                            {
                                code2Bind.Add(c2, bit24);
                                bBuffDataChange = true;
                            }
                        }
                        break;
                    default:
                        break;
                }
                frmExp = null;
            }
            else
            {
                frmExp = null;
            }
        }

        private void lbQtyTotal_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FrmAllRltCodes frm = new FrmAllRltCodes();
            frmAllCode = frm;
            frmAllCode.CodesBinded = new Dictionary<string, string>(codeBinded);

            if (frm.ShowDialog() == DialogResult.OK)
            {
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string msg = string.Empty;
            string batch = CallCtrlWithThreadSafety.GetText(txtBatch, this);
            string pzwh = CallCtrlWithThreadSafety.GetText(txtPZWH, this);

            //加载历史扫描数据
            worker.ReportProgress(0, "加载历史数据...\r\n");
            int cnt = Convert.ToInt32(SqlHelper.ExecuteScalar($"SELECT count(id) FROM [CodeRltInfo] where batch = '{batch}' and pzwh='{pzwh}'", ref msg));
            int pages = cnt == 0 ? 0 : (cnt - 1) / 1000 + 1;

            if (pages > 0)
            {
                DataTable dt;
                for (int i = 1; i <= pages; i++)
                {
                    dt = QueryPage("CodeRltInfo", i, 1000, $"batch = '{batch}' and pzwh='{pzwh}'", ref msg);
                    worker.ReportProgress(i * 100 / pages, ".");

                    if (dt!=null && dt.Rows.Count>0)
                    {
                        foreach (DataRow item in dt.Rows)
                        {
                            codeBinded.Add(item["rltCode"].ToString(), item["code"].ToString());
                        }
                    }
                }
            }
            else
            {
                worker.ReportProgress(100, "加载历史数据完成.\r\n");
            }

            if (string.IsNullOrEmpty(msg))
            {
                e.Result = null;
                //worker.ReportProgress(100, "加载完成！");
            }
            else
            {
                e.Result = "加载失败：" + msg;
            }
        }

        public DataTable QueryPage(string tbName, int page, int pageSize, string whereString, ref string msg)
        {
            string sql = string.Format("SELECT w2.n, w1.* FROM {0} w1, (SELECT TOP {1} row_number() OVER (ORDER BY ID DESC) n, ID FROM {2} where {4}) w2 WHERE w1.ID = w2.ID AND w2.n > {3} ORDER BY w2.n ASC ", 
                tbName, (page) * pageSize, tbName, (page - 1) * pageSize, whereString);

            return SqlHelper.ExecuteTable(sql, ref msg);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progBar.Close();
            btnRun.Enabled = true;

            if (e.Result != null)
            {

                MessageBox.Show(e.Result.ToString());
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("操作取消");
            }
            else
            {
                bIsRunning = true;
                btnRun.Text = "停止";
                btnRun.BackColor = Color.Red;
                strBatch = txtBatch.Text;
                strPZWH = txtPZWH.Text;
                btnExp.Enabled = true;

                serialPort1.DiscardInBuffer();
                serialPort1.DataReceived += serialPort1_DataReceived;
                //serialPort2.DataReceived += serialPort2_DataReceived;
                client.DataReceived += Client_DataReceived;

                lbQtyTotal.Text = codeBinded.Count.ToString();
                batchOld = txtBatch.Text.Trim();

                ConfigurationHelper.AppSet("batch", strBatch);
                ConfigurationHelper.AppSet("pzwh", strPZWH);

                txtBatch.Enabled = !bIsRunning;
                txtPZWH.Enabled = !bIsRunning;
            }
        }

        public void AppendMsg(string s)
        {
            logQty++;
            string log = string.Format("[{0}] {1}\r\n", DateTime.Now.ToString("HH:mm:ss"), s);
            Console.WriteLine(log);

            if (logQty > 200)
            {
                logQty = 0;
                CallCtrlWithThreadSafety.SetText(txtMsg, log, this);
            }
            else
            {
                CallCtrlWithThreadSafety.AppendText(txtMsg, log, this);
            }


        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ticks++;

            if (bBuffDataChange)
            {
                lbQtyBuff1.Text = codeZS.Count.ToString();
                lbQtyBuff2.Text = codeRlt.Count.ToString();
                bBuffDataChange = false;
            }

            if (codeRlt.Count>0 && codeZS.Count>0)
            {
                string c1 = "", c2 = "";

                bool b1 = codeZS.TryDequeue(out c1);

                if (b1)
                {
                    while (!codeRlt.TryDequeue(out c2)) ;

                    if (c1.Equals(cmdFail, StringComparison.OrdinalIgnoreCase) || c2.Equals(cmdFail, StringComparison.OrdinalIgnoreCase))
                    {

                    }
                    else
                    {
                        lock (objPrc)
                        {
                            code2Bind.Add(c2, c1);
                            
                        }
                        
                    }

                    bBuffDataChange = true;
                }
            }

            if (ticks*timer1.Interval%2000 == 0)
            {//2秒触发一次
                if (code2Bind.Count>0)
                {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(s=> 
                        {
                            string err = "";
                            List<string> sqls = new List<string>();
                            lock (objPrc)
                            {
                                
                                foreach (var key in code2Bind.Keys)
                                {
                                    sqls.Add($"insert into [CodeRltInfo]([code],[rltCode],[batch],[codeState],[inTime],[pzwh]) values('{code2Bind[key]}','{key}','{strBatch}',0,GETDATE(), '{strPZWH}')");
                                    codeBinded.Add(key, code2Bind[key]);
                                }

                                code2Bind.Clear();
                                bBuffDataChange = true;
                            }

                            if (sqls.Count>0)
                            {
                                if (!SqlHelper.ExecuteSqlTran(sqls.ToArray(), ref err))
                                {
                                    AppendExp("数据写入失败：" + err);
                                }
                                else
                                {
                                    CallCtrlWithThreadSafety.SetText(lbQtyTotal,codeBinded.Count.ToString(), this);
                                }
                            }
                            
                        }));
                }
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定复位？") == DialogResult.OK)
            {
                bReset = true;
            }
            
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string c1 = serialPort1.ReadLine();
            c1 = c1.Substring(1);//去掉前缀

            if (c1.Equals(cmdFail, StringComparison.OrdinalIgnoreCase))
            {
                AppendLog($"追溯码读码失败");
                codeZS.Enqueue(cmdFail);
            }
            else
            {
                if (!SYZSCheck24Bit(c1))
                {
                    Pick();
                    AppendLog($"追溯码非法：{c1}");
                    codeZS.Enqueue(cmdFail);
                }
                else
                {
                    string bit24 = SYZSGet24Bit(c1);

                    if (codeBinded.ContainsValue(bit24) || code2Bind.ContainsValue(bit24))
                    {
                        Pick();
                        AppendLog($"追溯码重复：{c1}");
                        codeZS.Enqueue(cmdFail);
                    }
                    else
                    {
                        if (bCheckPZWH)
                        {
                            //判断文号
                            string pzwh = SYZSGetPZWH(c1);
                            if (strPZWH.Equals(pzwh))
                            {
                                codeZS.Enqueue(bit24);
                            }
                            else
                            {
                                Pick();
                                AppendLog($"追溯码文号不匹配：{c1}");
                                codeZS.Enqueue(cmdFail);
                            }
                        }
                        else
                        {
                            codeZS.Enqueue(bit24);
                        }
                        
                    }
                    
                }

            }

            bBuffDataChange = true;
        }

        //private void serialPort2_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        //{
        //    string c2 = serialPort2.ReadLine();
            
        //    c2 = c2.Substring(1);//去掉前缀

        //    if (c2.Equals(cmdFail, StringComparison.OrdinalIgnoreCase))
        //    {
        //        Pick();
        //        AppendLog($"瓶盖码读码失败");
        //        codeRlt.Enqueue(cmdFail);
        //    }
        //    else
        //    {
        //        if (codeBinded.ContainsKey(c2) || code2Bind.ContainsKey(c2))
        //        {
        //            Pick();
        //            AppendLog($"瓶盖码重复：{c2}");
        //            codeRlt.Enqueue(cmdFail);
        //        }
        //        else
        //        {
        //            codeRlt.Enqueue(c2);
        //        }

        //    }

        //}

        private void serialPort3_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (frmExp!=null && frmExp.Visible)
            {
                try
                {
                    string l = serialPort3.ReadLine();
                    
                    frmExp.AppendCode(l);
                    return;
                }
                catch (Exception)
                {

                }
                
            }

            if (frmAllCode != null && frmAllCode.Visible)
            {
                try
                {
                    string l = serialPort3.ReadLine();
                    if (l.Length>=24)
                    {
                        frmAllCode.AppendCode(SYZSGet24Bit(l));
                    }
                    else
                    {
                        frmAllCode.AppendCode(l);
                    }
                    return;
                }
                catch (Exception)
                {

                }

            }

            handQty++;

            if (handQty == 1)
            {
                h1 = serialPort3.ReadLine();
                AppendLog("手持扫入：" + h1);
            }

            if (handQty == 2)
            {
                h2 = serialPort3.ReadLine();
                handQty = 0;
                AppendLog("手持扫入：" + h2);
                if (SYZSCheck24Bit(h1))
                {
                    string bit24 = SYZSGet24Bit(h1);
                    string key = h2;
                    if (codeBinded.ContainsKey(key) || code2Bind.ContainsKey(key))
                    {
                        if (codeBinded[key].Equals(bit24) || code2Bind[key].Equals(bit24))
                        {
                            AppendLog("关联成功");
                        }
                        else
                        {
                            AppendLog("关联失败!!!!!!!");
                        }
                    }
                    else
                    {
                        AppendExp($"查询关联失败：瓶盖码未找到{key}");
                    }
                }
                else if(SYZSCheck24Bit(h2))
                {
                    string bit24 = SYZSGet24Bit(h2);
                    string key = h1;

                    if (codeBinded.ContainsKey(key) || code2Bind.ContainsKey(key))
                    {
                        if (codeBinded[key].Equals(bit24) || code2Bind[key].Equals(bit24))
                        {
                            AppendLog("关联成功");
                        }
                        else
                        {
                            AppendLog("关联失败!!!!!!!");
                        }
                    }
                    else
                    {
                        AppendExp($"查询关联失败：瓶盖码未找到{key}");
                    }
                }
                else
                {
                    AppendExp($"追溯数据非法：{h1},{h2}");
                }
            }
        }

        void Pick()
        {
            serialPort1.Write(cmdPick);
            string s = CallCtrlWithThreadSafety.GetText(lbQtyPick, this);
            int qty = Convert.ToInt32(s);

            qty++;

            CallCtrlWithThreadSafety.SetText(lbQtyPick, qty.ToString(), this);
        }

        private bool SYZSCheck24Bit(string code)
        {
            return ValidateHelper.IsMatch(code, codeReg);
        }

        private string SYZSGet24Bit(string code)
        {
            return ValidateHelper.Match(code, codeReg);
        }

        private  string SYZSGetPZWH(string code)
        {
            string[] items = code.Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries);

            if (items.Length >= 5)
            {
                return items[items.Length - 3];
            }
            else if (items.Length == 2)
            {
                return items[1];
            }
            else
            {
                return code;
            }
        }
    }
}
